package com.littlepay.kr4.paulin.dfeba77;

import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.InputFilter;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.common.design.MaterialDialog;
import com.getbase.floatingactionbutton.FloatingActionButton;
import com.getbase.floatingactionbutton.FloatingActionsMenu;
import com.github.florent37.materialviewpager.MaterialViewPager;
import com.github.florent37.materialviewpager.header.HeaderDesign;
import com.littlepay.kr4.paulin.dfeba77.service.PushService;
import com.littlepay.kr4.paulin.dfeba77.config.SqliteConfig;
import com.littlepay.kr4.paulin.dfeba77.fragment.RecyclerViewFragment;
import com.littlepay.kr4.paulin.dfeba77.utils.CSCalculators;
import com.littlepay.kr4.paulin.dfeba77.utils.CostPanelUtil;
import com.littlepay.kr4.paulin.dfeba77.utils.DateUtil;
import com.littlepay.kr4.paulin.dfeba77.utils.KeyboardUtil;
import com.littlepay.kr4.paulin.dfeba77.utils.PrefUtils;
import com.littlepay.kr4.paulin.dfeba77.utils.SqliteHelper;
import com.littlepay.kr4.paulin.dfeba77.entity.Sticker;
import com.littlepay.kr4.paulin.dfeba77.adapter.StickerAdapter;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;

import butterknife.BindView;
import butterknife.ButterKnife;

import static android.provider.MediaStore.Files.FileColumns.MEDIA_TYPE_IMAGE;

public class MainActivity extends DrawerActivity {

    @Override
    protected void onResume() {
        super.onResume();
        setHeadCount();

    }

    @BindView(R.id.materialViewPager)
    MaterialViewPager mViewPager;
    //三个layout用于显示剩余和今日花费，以及输入消费的切换
    LinearLayout costlayout;
    LinearLayout surpluslayout;
    LinearLayout inputLayout;
    //带有键盘和输入消费盘的layout
    RelativeLayout add_cost;
    //
    EditText editTextInput;//新消费输入框
    TextView editTextCost;
    TextView editTextSurplus;
    FloatingActionButton fabSetting,fabAnal;
    public static FloatingActionsMenu fabMenu;
    RelativeLayout fabLayout;
    RelativeLayout keyboardPanel;
    GridView cost_panel;
    private RecyclerView mRecyclerView;
    public static RecyclerViewFragment recyclerViewFragment;
    //判断登录标志变量，从sharepreference获取
    private Boolean isLogin = false;
    //TODO:使用静态layout控件会导致内容溢出？如何处理
    //public static RelativeLayout fabLayout;
    String phone;
    public static boolean isdisplay = true;


    float x1 = 0;
    float x2 = 0;
    float y1 = 0;
    float y2 = 0;
    private long exitTime = 0;


    /*返回键的收起输入和退出应用的功能*/
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(keyCode == KeyEvent.KEYCODE_BACK){
            if(inputLayout.getVisibility() == View.VISIBLE || add_cost.getVisibility() == View.VISIBLE){
                inputLayout.setVisibility(View.GONE);
                surpluslayout.setVisibility(View.VISIBLE);
                add_cost.setVisibility(View.GONE);
                //返回主页显示FAB
                fabMenu.setVisibility(View.VISIBLE);
                isdisplay = true;
                return true;
            }
            if(event.getAction() == KeyEvent.ACTION_DOWN){
                if((System.currentTimeMillis()-exitTime) > 2000){
                    //TODO：Toast在安卓7.0的S7E上无法正确显示,某时候又能正确显示，
                    // Activity中不要getApplicationcontent()否则导致toast位置不正确
                    Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
                    exitTime = System.currentTimeMillis();
                } else {
                    finish();
                    System.exit(0);
                }
                return true;
            }
        }
            return super.onKeyDown(keyCode,event);
        }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Intent intent = new Intent(this,PushService.class);
        startService(intent);

        setTitle("");
        ButterKnife.bind(this);
        /*头部Logo部分 包含了:
        * 花费：cost
        * 剩余：surplus
        * 输入：input
        * 如下所示：LISTED BELOW
        * */
        costlayout = (LinearLayout) findViewById(R.id.head_cost);
        surpluslayout = (LinearLayout) findViewById(R.id.head_surplus);
        inputLayout = (LinearLayout) findViewById(R.id.head_input);

        editTextInput = (EditText)findViewById(R.id.cost_input);
        editTextCost  = (TextView)findViewById(R.id.text_view_cost);
        editTextSurplus = (TextView)findViewById(R.id.text_view_surplus);
        setHeadCount();
        /*添加新的消费部分 包含:
        * GridView -select attribution（选择消费类型）
        * LinerLayout - with a button to select date（选择日期）
        * Inner_keyboard - input new cost（内部输入法，快速启动使用）
        * */
        add_cost = (RelativeLayout) findViewById(R.id.add_cost);
        /*FAB部分
        * */
        fabSetting = (FloatingActionButton) findViewById(R.id.action_user);
        fabAnal = (FloatingActionButton) findViewById(R.id.action_analysis);
        fabMenu = (FloatingActionsMenu) findViewById(R.id.multiple_actions);
        fabLayout = (RelativeLayout) findViewById(R.id.fab_layout);
//        fabLayout.setOnLongClickListener(new View.OnLongClickListener() {
//            @Override
//            public boolean onLongClick(View view) {
//                Toast.makeText(MainActivity.this,"long click!",Toast.LENGTH_SHORT).show();
//                return true;
//            }
//        });
        fabSetting.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent  = new Intent(MainActivity.this,SettingActivity.class);
                startActivity(intent);
                fabMenu.collapse();
            }
        });
        fabAnal.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent  = new Intent(MainActivity.this,OverviewActivity.class);
                startActivity(intent);
                fabMenu.collapse();
            }
        });
        fabSetting.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View view) {
                //Toast.makeText(MainActivity.this,"fab long click!",Toast.LENGTH_SHORT).show();
////                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//                String strImgPath = "";//照片保存路径
//                Intent getPhoto = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//                strImgPath = Environment.getExternalStorageDirectory()
//                        .toString() + "/littlepay/";
//                String fileName = new SimpleDateFormat("yyyyMMdd_HHmmss")
//                        .format(new Date()) + ".jpg";// 照片以格式化日期方式命名
//                File out = new File(strImgPath);
//                if (!out.exists()) {
//                    out.mkdirs();
//                }
//                out = new File(strImgPath, fileName);
//                strImgPath = strImgPath + fileName;// 该照片的绝对路径
//                Uri uri = Uri.fromFile(out);
//                getPhoto.putExtra(MediaStore.EXTRA_OUTPUT, uri);//根据uri保存照片
//                getPhoto.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);//保存照片的质量
//                startActivityForResult(getPhoto, 1);//启动相机拍照
//                startActivityForResult(intent, 101);
                String dict = "/DCIM/littlepay";
                String path = Environment.getExternalStorageDirectory().toString()
                        + dict;
                File tempFile = new File(path);
                if (!tempFile.exists()) {
                    tempFile.mkdirs();
                }
                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                if (android.os.Build.VERSION.SDK_INT <= 24) {
                    // 从文件中创建uri
//                    Uri uri = Uri.fromFile(tempFile);
//                    intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
                    Uri mOutPutFileUri;
                    File file = new File(tempFile, System.currentTimeMillis() + ".jpg");
                    mOutPutFileUri = Uri.fromFile(file);
                    intent.putExtra(MediaStore.EXTRA_OUTPUT, mOutPutFileUri);
                } else {
                    //兼容android7.0 使用共享文件的形式
                    ContentValues contentValues = new ContentValues(1);
                    contentValues.put(MediaStore.Images.Media.DATA, tempFile.getAbsolutePath());
                    Uri uri = getApplication().getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues);
                    intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
                }

                Toast.makeText(getApplication(),"照片存储位置为："+ dict ,Toast.LENGTH_LONG).show();
                startActivityForResult(intent, 1);
                fabMenu.collapse();
                return true;
            }
        });
//        fabMenu.setOnLongClickListener(new View.OnLongClickListener() {
//            @Override
//            public boolean onLongClick(View view) {
//                Toast.makeText(MainActivity.this,"fab long click!",Toast.LENGTH_SHORT).show();
//                return false;
//            }
//        });

        /*花费盘部分
        * */
        keyboardPanel = (RelativeLayout) findViewById(R.id.keyboard_top_panel);
        cost_panel = (GridView) findViewById(R.id.cost_select);
        //fabLayout = (RelativeLayout) findViewById(R.id.fab_layout);
        //get the recycleView
        mRecyclerView = (RecyclerView) LayoutInflater.from(this).inflate(R.layout.fragment_recyclerview,null).findViewById(R.id.recyclerView);



        final Toolbar toolbar = mViewPager.getToolbar();
        if (toolbar != null) {
            setSupportActionBar(toolbar);
        }

        mViewPager.getViewPager().setAdapter(new FragmentStatePagerAdapter(getSupportFragmentManager()) {

            @Override
            public Fragment getItem(int position) {
                switch (position % 4) {
                    //case 0:
                    //    return RecyclerViewFragment.newInstance();
                    //case 1:
                    //    return RecyclerViewFragment.newInstance();
                    //case 2:
                    //    return WebViewFragment.newInstance();
                    default:
                        return recyclerViewFragment = RecyclerViewFragment.newInstance();
                }
            }

            @Override
            public int getCount() {
                return 1;
            }

//            @Override
//            public CharSequence getPageTitle(int position) {
//                switch (position % 4) {
//                    case 0:
//                        return "Selection";
//                    case 1:
//                        return "Actualités";
//                    case 2:
//                        return "Professionnel";
//                    case 3:
//                        return "Divertissement";
//                }
//                return "";
//            }
        });
        //TODO:add stripe to the headStripe
        //add success by set imageview to material_view_pager_layout
        mViewPager.setMaterialViewPagerListener(new MaterialViewPager.Listener() {
            @Override
            public HeaderDesign getHeaderDesign(int page) {
///*
//                switch (page) {
//                    case 0:
//                        return HeaderDesign.fromColorResAndUrl(
//                            R.color.light_blue,
//                            "http://phandroid.s3.amazonaws.com/wp-content/uploads/2014/06/android_google_moutain_google_now_1920x1080_wallpaper_Wallpaper-HD_2560x1600_www.paperhi.com_-640x400.jpg");
//                    case 1:
//                        return HeaderDesign.fromColorResAndUrl(
//                            R.color.blue,
//                            "http://www.hdiphonewallpapers.us/phone-wallpapers/540x960-1/540x960-mobile-wallpapers-hd-2218x5ox3.jpg");
//                    case 2:
//                        return HeaderDesign.fromColorResAndUrl(
//                            R.color.cyan,
//                            "http://www.droid-life.com/wp-content/uploads/2014/10/lollipop-wallpapers10.jpg");
//                    case 3:
//                        return HeaderDesign.fromColorResAndUrl(
//                            R.color.red,
//                            "http://www.tothemobile.com/wp-content/uploads/2014/07/original.jpg");
//                }
//*/
//
//                //execute others actions if needed (ex : modify your header logo)
//
//                //return null;
                return HeaderDesign.fromColorRes(
                        R.color.light_blue);
            }
        });
        //只有一个页面不需要多页面适配器，否则布局混乱
//        mViewPager.getViewPager().setOffscreenPageLimit(mViewPager.getViewPager().getAdapter().getCount());
//        mViewPager.getPagerTitleStrip().setViewPager(mViewPager.getViewPager());
        //no need to use
        final View logo = findViewById(R.id.logo_white);
        if (logo != null) {
            logo.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mViewPager.notifyHeaderChanged();
                    changeDisplay();
                }
            });
            logo.setOnTouchListener(new View.OnTouchListener() {
                @Override
                public boolean onTouch(View view, MotionEvent motionEvent) {
                    if(motionEvent.getAction() == MotionEvent.ACTION_DOWN) {
                        //当手指按下的时候
                        x1 = motionEvent.getX();
                        y1 = motionEvent.getY();
                    }if(motionEvent.getAction() == MotionEvent.ACTION_UP) {
                        //当手指离开的时候
                        x2 = motionEvent.getX();
                        y2 = motionEvent.getY();
                        //以此基础的获取滑向四个方向
                        if(y1 - y2 > 50) {
                            //Toast.makeText(getApplicationContext(), "向上滑", Toast.LENGTH_SHORT).show();
                        } else if(y2 - y1 > 150 ) {
                            //Toast.makeText(getApplicationContext(), "向下滑", Toast.LENGTH_SHORT).show();
                            //进入输入模式
                            inputMode();
                            //editTextInput.requestFocus();
                        } else if(x1 - x2 > 50) {
                            //Toast.makeText(getApplicationContext(), "向左滑", Toast.LENGTH_SHORT).show();
                        } else if(x2 - x1 > 50) {
                            //Toast.makeText(getApplicationContext(), "向右滑", Toast.LENGTH_SHORT).show();
                        }
                    }
                    return false;

                }
            });
        }
        if(keyboardPanel != null){
            keyboardPanel.setOnTouchListener(new View.OnTouchListener() {
                @Override
                public boolean onTouch(View view, MotionEvent motionEvent) {
                    if(motionEvent.getAction() == MotionEvent.ACTION_DOWN) {
                        //当手指按下的时候
                        x1 = motionEvent.getX();
                        y1 = motionEvent.getY();
                    }if(motionEvent.getAction() == MotionEvent.ACTION_UP) {
                        //当手指离开的时候
                        x2 = motionEvent.getX();
                        y2 = motionEvent.getY();
                        //以此基础的获取滑向四个方向
                        if(y1 - y2 > 50) {
                            //Toast.makeText(getApplicationContext(), "向上滑", Toast.LENGTH_SHORT).show();
                        } else if(y2 - y1 > 150 ) {
                            //Toast.makeText(getApplicationContext(), "向下滑", Toast.LENGTH_SHORT).show();
                            //进入输入模式
                            displayMode();
                            //editTextInput.requestFocus();
                        } else if(x1 - x2 > 50) {
                            //Toast.makeText(getApplicationContext(), "向左滑", Toast.LENGTH_SHORT).show();
                        } else if(x2 - x1 > 50) {
                            //Toast.makeText(getApplicationContext(), "向右滑", Toast.LENGTH_SHORT).show();
                        }
                    }
                    return false;

                }
            });
        }
        cost_panel.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            String detail = "";
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                //TODO：应该针对不同点击项目有不同响应事件
                // （必做）借出有个输入对话框输入
                // 吃饭，出行，购物，娱乐，住宿均有长按跳出list选择的操作，这个可以在不影响Attri的操作情况下使用detail来补全
                // 比如说都是吃饭，attri都是1但是有不同的detail的时候，展示的时候应该以detail中存储字符串为准
                if(!editTextInput.getText().toString().equals("")){
                    // cost是插入sqlite用的，cost_sticker是用来显示的，因为存储均用整形保证数据精度
                    // INT*0.01，/100会丢失两位小数点
                    final double cost_sticker = Double.parseDouble(editTextInput.getText().toString());
                    final int cost = (int)(cost_sticker*100);
                    final int attri = StickerAdapter.getAttri(i);
                    //String detail = "";
                    if(detail.isEmpty()){
                        detail = "";
                    }
                    final String DialogTitle;
                    switch (i) {
                        //自定义和借出必须填内容
                        case 0:
                        case 6:
                            if (i == 6) {
                                DialogTitle = "借给了谁：";
                            } else {
                                DialogTitle = "输入自定义内容：";
                            }
                            final EditText editTextDetail = new EditText(MainActivity.this);
                            editTextDetail.setTextColor(getResources().getColor(R.color.lightslategray));
                            editTextDetail.setFilters(new InputFilter[]{ new  InputFilter.LengthFilter(6)});
                            new MaterialDialog.Builder(MainActivity.this)
                                    .setTitle(DialogTitle)
                                    .setContentView(editTextDetail)
                                    .setNegativeButton("取消", null)
                                    .setPositiveButton("确定", new MaterialDialog.OnClickListener() {
                                        @Override
                                        public boolean onClick(DialogInterface dialog, int which) {
                                            detail = editTextDetail.getText().toString();
                                            if (detail.isEmpty()) {
                                                Toast.makeText(MainActivity.this, "请输入内容", Toast.LENGTH_SHORT).show();
                                            } else {
                                                //Toast.makeText(MainActivity.this, DialogTitle + detail, Toast.LENGTH_SHORT).show();
                                                insertStickerBySqlite(cost,attri,cost_sticker,detail);
                                                displayMode();
                                                detail = "";
                                                return false;
                                            }
                                            return true;
                                        }
                                    }).show();
                            break;
                        case 1:
                        case 2:
                        case 3:
                        case 4:
                        case 5:
                        case 7:
                        case 8:
                        case 9:
                            insertStickerBySqlite(cost,attri,cost_sticker,detail);
                            displayMode();
                            break;
                        default:
                            displayMode();
                            break;
                    }
//                    //统一获取日期，让显示在recycleview和存入数据库的数据时间戳一致
//                    String date = DateUtil.getNowDate();
//                    long result = -1;//判断插入本地sqlite结果，返回值是long
//                    SqliteHelper sqliteHelper = new SqliteHelper(MainActivity.this , SqliteConfig.SQLITE_DATABASE_FILE_NAME , null ,1);
//                    //insertData返回受影响的行数
//                    result = sqliteHelper.insertData(cost,attri,detail,date);
//                    if(result > -1){
//                        Toast.makeText(getApplicationContext(), "新纪录添加成功", Toast.LENGTH_SHORT).show();
//                        setHeadCount();
//                    }
//                    Sticker sticker = new Sticker();
//                    sticker.setCost(cost_sticker);
//                    sticker.setAttribution(attri);
//                    sticker.setDetail(detail);
//                    sticker.setDate(date);
//                    //Toast.makeText(MainActivity.this,"cost(int) = "+cost+"cost(set)="+cost_sticker,Toast.LENGTH_SHORT).show();
//                    //System.out.println("origin="+ editTextInput.getText().toString()+"\ncost = "+cost+"\ncost_sticker="+cost_sticker);
//                    //new RecyclerViewFragment().InsertItem(sticker);
//                    //添加数据并移动位置
//                    recyclerViewFragment.getRecyclerViewAdapter().insertOneItem(sticker);
                    //insertStickerBySqlite(cost,attri,cost_sticker,detail);
                    //displayMode();
                }else{
                    Toast.makeText(MainActivity.this,"先输入消费再选择类型",Toast.LENGTH_SHORT).show();
                }

            }
        });
        cost_panel.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {

                if(!editTextInput.getText().toString().equals("")) {
                    String detail = "";
                    final double cost_sticker = Double.parseDouble(editTextInput.getText().toString());
                    final int cost = (int)(cost_sticker*100);
                    final int attri = StickerAdapter.getAttri(i);
                    //String detail = "";
                    if(detail.isEmpty()){
                        detail = "";
                    }
                    switch (i) {
                        case 1://吃饭
                            final String[] item1 = {"早餐", "午餐", "晚餐", "零食", "其他"};
                            new MaterialDialog.Builder(MainActivity.this)
                                    .setItems(item1, new MaterialDialog.OnClickListener() {
                                        @Override
                                        public boolean onClick(DialogInterface dialog, int which) {
                                            //Toast.makeText(MainActivity.this, item1[which], Toast.LENGTH_SHORT).show();
                                            insertStickerBySqlite(cost, attri, cost_sticker, item1[which]);
                                            displayMode();
                                            return false;
                                        }
                                    }).show();
                            break;
                        case 2://出行
                            final String[] item2 = {"航班", "轮渡", "火车", "打车", "公交", "加油", "其他"};
                            new MaterialDialog.Builder(MainActivity.this)
                                    .setItems(item2, new MaterialDialog.OnClickListener() {
                                        @Override
                                        public boolean onClick(DialogInterface dialog, int which) {
                                            //Toast.makeText(MainActivity.this, item2[which], Toast.LENGTH_SHORT).show();
                                            insertStickerBySqlite(cost, attri, cost_sticker, item2[which]);
                                            displayMode();
                                            return false;
                                        }
                                    }).show();
                            break;
                        case 3://购物
                            final String[] item3 = {"淘宝", "京东", "便利店", "超市", "其他"};
                            new MaterialDialog.Builder(MainActivity.this)
                                    .setItems(item3, new MaterialDialog.OnClickListener() {
                                        @Override
                                        public boolean onClick(DialogInterface dialog, int which) {
                                            //Toast.makeText(MainActivity.this, item3[which], Toast.LENGTH_SHORT).show();
                                            insertStickerBySqlite(cost, attri, cost_sticker, item3[which]);
                                            displayMode();
                                            return false;
                                        }
                                    }).show();
                            break;
                        case 4://娱乐
                            final String[] item4 = {"咖啡", "KTV", "聚会", "酒吧", "其他"};
                            new MaterialDialog.Builder(MainActivity.this)
                                    .setItems(item4, new MaterialDialog.OnClickListener() {
                                        @Override
                                        public boolean onClick(DialogInterface dialog, int which) {
                                            //Toast.makeText(MainActivity.this, item4[which], Toast.LENGTH_SHORT).show();
                                            insertStickerBySqlite(cost, attri, cost_sticker, item4[which]);
                                            displayMode();
                                            return false;
                                        }
                                    }).show();
                            break;
                        case 5://住宿
                            final String[] item5 = {"水费", "电费", "供暖费", "其他"};
                            new MaterialDialog.Builder(MainActivity.this)
                                    .setItems(item5, new MaterialDialog.OnClickListener() {
                                        @Override
                                        public boolean onClick(DialogInterface dialog, int which) {
                                            //Toast.makeText(MainActivity.this, item5[which], Toast.LENGTH_SHORT).show();
                                            insertStickerBySqlite(cost, attri, cost_sticker, item5[which]);
                                            displayMode();
                                            return false;
                                        }
                                    }).show();
                            break;
                        default:
                            break;
                    }
                }else {
                    Toast.makeText(MainActivity.this,"先输入消费再选择类型",Toast.LENGTH_SHORT).show();
                }
                return true;
            }
        });

    }
   /* 进入展示花费模式（收起所有其他页面）*/
    public void displayMode(){
        if(!PrefUtils.getContinuousSticker()){
            inputLayout.setVisibility(View.GONE);
            surpluslayout.setVisibility(View.VISIBLE);
            add_cost.setVisibility(View.GONE);
            //返回主页显示FAB
            fabMenu.setVisibility(View.VISIBLE);
            isdisplay = true;
        }
        editTextInput.setText("");
    }

    /* 进入展示输入消费模式，打开对应界面*/
    public void inputMode(){
        surpluslayout.setVisibility(View.GONE);
        costlayout.setVisibility(View.GONE);
        editTextInput.setText("");
        inputLayout.setVisibility(View.VISIBLE);
        add_cost.setVisibility(View.VISIBLE);
        //TODO:是否需要回收输入法和花费盘
        new KeyboardUtil(MainActivity.this,getApplicationContext(), editTextInput).showKeyboard();
        new CostPanelUtil(MainActivity.this,getApplicationContext()).showCostPanel();
        //进入输入界面，不需要FAB
        fabMenu.setVisibility(View.GONE);
        isdisplay = false;
    }

    /*只有在不在输入模式情况才能切换*/
    public void changeDisplay(){
        if(inputLayout.getVisibility() ==View.GONE){
            if(costlayout.getVisibility() == View.GONE ){
                //显示花费
                surpluslayout.setVisibility(View.GONE);
                costlayout.setVisibility(View.VISIBLE);
            }else if(surpluslayout.getVisibility() == View.GONE ){
                //显示剩余
                costlayout.setVisibility(View.GONE);
                surpluslayout.setVisibility(View.VISIBLE);
            }
        }
    }

    private void setHeadCount(){
        CSCalculators.refreshAll();
        editTextCost.setText(String.valueOf((int)CSCalculators.costDay));
        editTextSurplus.setText(String.valueOf((int)CSCalculators.surplusDay));
    }

    private long insertStickerBySqlite(int cost,int attri,double cost_sticker,String detail){
        //统一获取日期，让显示在recycleview和存入数据库的数据时间戳一致
        String date = DateUtil.getNowDate();
        long result = -1;//判断插入本地sqlite结果，返回值是long
        SqliteHelper sqliteHelper = new SqliteHelper(MainActivity.this , SqliteConfig.SQLITE_DATABASE_FILE_NAME , null ,1);
        //insertData返回受影响的行数
        result = sqliteHelper.insertData(cost,attri,detail,date);
        if(result > -1){
            Toast.makeText(getApplicationContext(), "纪录添加成功", Toast.LENGTH_SHORT).show();
            setHeadCount();
        }else {
            Toast.makeText(getApplicationContext(), "记录添加失败", Toast.LENGTH_SHORT).show();
        }
        Sticker sticker = new Sticker();
        sticker.setCost(cost_sticker);
        sticker.setAttribution(attri);
        sticker.setDetail(detail);
        sticker.setDate(date);
        //Toast.makeText(MainActivity.this,"cost(int) = "+cost+"cost(set)="+cost_sticker,Toast.LENGTH_SHORT).show();
        //System.out.println("origin="+ editTextInput.getText().toString()+"\ncost = "+cost+"\ncost_sticker="+cost_sticker);
        //new RecyclerViewFragment().InsertItem(sticker);
        //添加数据并移动位置
        recyclerViewFragment.getRecyclerViewAdapter().insertOneItem(sticker);
        return result;
    }
}

